//
//  gtMapGeoCodeSearchHandle.m
//  zjkd
//
//  Created by app on 17/2/21.
//  Copyright © 2017年 gtexpress. All rights reserved.
//

#import "gtMapGeoCodeSearchHandle.h"

@interface gtMapGeoCodeSearchHandle ()<BMKGeoCodeSearchDelegate>

@property (nonatomic,strong)BMKGeoCodeSearch * bmkGeoCodeSearch;

@end



@implementation gtMapGeoCodeSearchHandle
- (BMKGeoCodeSearch *)bmkGeoCodeSearch
{
    if (!_bmkGeoCodeSearch) {
        _bmkGeoCodeSearch = [[BMKGeoCodeSearch alloc]init];
        _bmkGeoCodeSearch.delegate = self;
    }
    return _bmkGeoCodeSearch;
}

- (void)startGeoSearchWithExpressInfoModel:(GTSendExpressInfomationModel *)model
{
    NSString * cityName = model.senderCityName;
    NSString * address = [NSString stringWithFormat:@"%@%@",model.senderDistrictName,model.senderAddress];
    BMKGeoCodeSearchOption *geoCodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geoCodeSearchOption.address = address;
    geoCodeSearchOption.city = cityName;
    geoCodeSearchOption.address = @"北京市";
    BOOL flag = [self.bmkGeoCodeSearch geoCode:geoCodeSearchOption];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
        if ([self.geoDelegate respondsToSelector:@selector(geoCodeCallBackWithType:andLocation:)]) {
            [self.geoDelegate geoCodeCallBackWithType:gtMapGeoCodeSearchFailure andLocation:CLLocationCoordinate2DMake(0 , 0)];
        }

    }
}

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        if ([self.geoDelegate respondsToSelector:@selector(geoCodeCallBackWithType:andLocation:)]) {
            [self.geoDelegate geoCodeCallBackWithType:gtMapGeoCodeSearchSuccess andLocation:[gtMapGeoCodeSearchHandle GCJ02FromBD09:result.location]];
        }
        
    }
    else {
        NSLog(@"抱歉，未找到结果");
        if ([self.geoDelegate respondsToSelector:@selector(geoCodeCallBackWithType:andLocation:)]) {
            [self.geoDelegate geoCodeCallBackWithType:gtMapGeoCodeSearchNoResult andLocation:[gtMapGeoCodeSearchHandle GCJ02FromBD09:result.location]];
        }
    }
}


+ (CLLocationCoordinate2D)GCJ02FromBD09:(CLLocationCoordinate2D)coor
{
    CLLocationDegrees x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    CLLocationDegrees x = coor.longitude - 0.0065, y = coor.latitude - 0.006;
    CLLocationDegrees z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
    CLLocationDegrees theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
    CLLocationDegrees gg_lon = z * cos(theta);
    CLLocationDegrees gg_lat = z * sin(theta);
    return CLLocationCoordinate2DMake(gg_lat, gg_lon);
}


@end
